<!--
 * @Description: 
 * @Author: duan_shuangjun 丶
 * @Date: 2025-09-03 16:43:16
 * @LastEditTime: 2025-10-12 22:18:17
-->
<template>
  <div>
    <CustomDialog
      :visible.sync="isShowDialog"
      :isNotScroll="false"
      @close="onCancel"
      top="3vh"
      curentClass="bookCreateDialog-box"
    >
      <div class="dialog-content">
        <div class="title">{{ isEdit ? '修改预订' : '新增预订' }}</div>
        <el-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="0.7rem"
          label-position="right"
          class="el-form-wrap"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="顾客姓名" prop="user_name" required>
                <el-input v-model.trim="formData.user_name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话" prop="mobile" required>
                <el-input
                  v-model.trim="formData.mobile"
                  placeholder="请输入手机号"
                  maxlength="11"
                  @input="handleMobileInput"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="用餐人数" prop="use_num" required>
                <el-input
                  v-model.number="formData.use_num"
                  type="number"
                  placeholder="请输入人数"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="用餐时间" prop="book_time" required>
                <el-date-picker
                  v-model="formData.book_time"
                  type="datetime"
                  placeholder="选择用餐时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="预留时长" prop="keep_time" required>
                <el-input
                  v-model.number="formData.keep_time"
                  type="number"
                  placeholder="请输入(至少30分钟)"
                  min="30"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="预订类型" prop="book_type" required>
                <el-select v-model="formData.book_type" placeholder="请选择">
                  <el-option
                    v-for="opt in typeOptions"
                    :key="opt.id"
                    :label="opt.name"
                    :value="opt.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="定金金额">
                <el-input v-model.number="formData.book_money" type="number" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开台方式" prop="settle_type" required>
                <el-select v-model="formData.settle_type" placeholder="请选择">
                  <el-option
                    v-for="opt in settleTypeOptions"
                    :key="opt.value"
                    :label="opt.label"
                    :value="opt.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单席金额" prop="money" :required="moneyRequired">
                <el-input v-model.number="formData.money" type="number" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="席数">
                <el-input
                  v-model.number="formData.book_num"
                  type="number"
                  placeholder="自动或手填"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="代订人">
                <el-input
                  v-model.trim="formData.subscription"
                  :placeholder="userStore.userInfo?.real_name || '系统自动带入'"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="选择桌台" prop="deskIds" required>
                <el-button class="big-btn" plain @click="openDesktopList">{{
                  selectedDeskCount > 0 ? `已选${selectedDeskCount}个` : '选择桌台'
                }}</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="支付方式">
                <el-select v-model="formData.pay_type" placeholder="请选择">
                  <el-option
                    v-for="opt in payTypeOptions"
                    :key="opt.value"
                    :label="opt.label"
                    :value="opt.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model.trim="formData.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-col>        
          </el-row>
        </el-form>
        <!-- 选择桌台时显示（对齐旧项目结构） -->
        <div class="select-desktop-wrap" v-if="showDeskList">
          <div class="room-selected-box">
            <!-- 骨架屏加载状态 -->
            <div v-if="deskListLoading" class="desk-skeleton-container">
              <div class="skeleton-desk-item" v-for="n in 8" :key="'skeleton-' + n">
                <el-skeleton animated>
                  <template #template>
                    <el-skeleton-item
                      variant="rect"
                      style="width: 220px; height: 210px; border-radius: 12px"
                    />
                  </template>
                </el-skeleton>
              </div>
            </div>
            <!-- 实际桌台列表 -->
            <div v-else-if="deskList && deskList.length" class="room-selected-scroll-list">
              <div
                class="scroll-selected-list-item"
                v-for="(desk, index) in deskList"
                :key="desk.id + '-' + index"
                @click.stop="toggleDesk(desk)"
              >
                <div class="title-box">
                  <div class="count">
                    <span>{{ desk.use_num || '0' }}</span
                    >/<span>{{ desk.capacity }}人</span>
                  </div>
                </div>
                <div class="desc-box">
                  <div class="numberAndTag">
                    <div class="number">{{ desk.name }}</div>
                  </div>
                </div>
                <img
                  v-show="desk.isChecked"
                  class="choose-img"
                  src="@/assets/images/home/xuanzhongzhuotai.png"
                  alt=""
                />
              </div>
              <div
                class="scroll-list-item-zhanwei"
                v-for="val in ['zw1', 'zw2', 'zw3', 'zw4']"
                :key="val"
              ></div>
            </div>
            <!-- 无数据状态 -->
            <div v-else class="no-desk-data">
              <div class="no-data-text">暂无可用桌台</div>
            </div>
          </div>
          <div class="count-selected-box" v-if="!deskListLoading && deskList && deskList.length">
            <div class="total">共{{ deskList.length }}台</div>
          </div>
        </div>

        <div class="footer">
          <el-button 
            class="footer-btn lg" 
            type="primary" 
            @click="openFoodOrder"
            :disabled="!canOpenFoodOrder"
          >
            {{ formData.foodList.length > 0 ? '已选' + formData.foodList.length + '个' : '选择菜品' }}
          </el-button>
          <el-button class="footer-btn lg" @click="onCancel">取消</el-button>
          <el-button
            class="footer-btn lg"
            type="primary"
            :loading="confirmLoading"
            @click="onConfirm"
            >确定</el-button
          >
        </div>
      </div>
    </CustomDialog>
  </div>
</template>
<script setup lang="ts">
import { computed, reactive, ref, watch, onMounted } from 'vue'
import { ElMessage, ElSkeleton } from 'element-plus'
import { useRouter } from 'vue-router'
import CustomDialog from '@/components/CustomDialog/Index.vue'
import { useUserStore } from '@/stores/user'

interface Props {
  modelValue: boolean
  actionType?: string
  editData?: any // 编辑时的数据
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  actionType: 'add',
  editData: null
})

const userStore = useUserStore()
const router = useRouter()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  onConfirmSuccess: []
}>()

const isShowDialog = computed({
  get() {
    return props.modelValue
  },
  set(v: boolean) {
    emit('update:modelValue', v)
  }
})

const isEdit = computed(() => props.actionType === 'edit')
const confirmLoading = ref(false)
const formRef = ref()

const formData = reactive({
  user_name: '',
  mobile: '',
  use_num: null as number | null,
  book_time: '',
  keep_time: null as number | null,
  book_type: null as number | null,
  book_money: null as number | null,
  settle_type: null as number | null,
  money: null as number | null,
  book_num: 0 as number,
  pay_type: '' as string | '',
  remark: '',
  deskIds: [] as number[],
  subscription: '' as string, // 代订人
  selectedFoods: [] as any[], // 选择的菜品
  foodList: [] as any[] // 选择的菜品
})

const rules = {
  user_name: [{ required: true, message: '请输入顾客姓名', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^\d{11}$/, message: '请输入11位手机号', trigger: 'blur' }
  ],
  use_num: [{ required: true, message: '请输入用餐人数', trigger: 'blur' }],
  book_time: [{ required: true, message: '请选择预订时间', trigger: 'change' }],
  keep_time: [{ required: true, message: '请输入预留时长', trigger: 'blur' }],
  book_type: [{ required: true, message: '请选择预订类型', trigger: 'change' }],
  settle_type: [{ required: true, message: '请选择开台方式', trigger: 'change' }],
  deskIds: [{ required: true, message: '请选择桌台', trigger: 'change' }],
  money: [
    {
      validator: (_: any, v: any, cb: any) => {
        // 开台方式 10=酒席方式 => 单席金额必填
        const need = formData.settle_type === 10
        if (need && (v === null || v === undefined || v === ''))
          return cb(new Error('请输入单席金额'))
        cb()
      },
      trigger: 'blur'
    }
  ]
}

const moneyRequired = computed(() => formData.settle_type === 10)

// 是否可以打开点菜页面（需要填写基本信息）
const canOpenFoodOrder = computed(() => {
  return formData.user_name && formData.mobile && formData.use_num && formData.book_time
})

const typeOptions = ref<any[]>([])

const settleTypeOptions = ref([
  { label: '酒席方式', value: 10 },
  { label: '散点方式', value: 20 }
])

const payTypeOptions = ref<any[]>([])

const selectedDeskCount = ref<number>(0)
const showDeskList = ref(false)
const deskList = ref<any[]>([])
const deskListLoading = ref(false)
import { deskBookDeskList, deskBookAdd, deskBookEdit, deskBookTypeList } from '@/api/book'
import { paymentList } from '@/api/pay'
const selectedDeskIds = ref<number[]>([])

// 通过查询详情接口填充编辑数据
async function fillEditData() {
  if (!props.editData?.id) return
  
  try {
    // 通过API查询最新的预约详情
    const { deskBookDetail } = await import('@/api/book')
    const res = await deskBookDetail({ book_id: props.editData.id })
    
    if (res?.status === 200) {
      const data = res.data.detail
      
      formData.user_name = data.user_name || ''
      formData.mobile = data.mobile || ''
      formData.use_num = data.use_num || null
      formData.book_time = data.book_time.text || ''
      formData.keep_time = data.keep_time || null
      formData.book_type = data.book_type || null
      formData.book_money = data.book_money || null
      formData.settle_type = data.settle_type.value || null
      formData.money = data.money || null
      formData.book_num = data.book_num || 0
      formData.pay_type = data.pay_type || ''
      formData.remark = data.remark || ''
      formData.deskIds = data.deskIds || []
      formData.selectedFoods = data.selectedFoods || []
      formData.subscription = props.editData.subscription || ''
      formData.foodList = data.food_list || []
      
      // 设置编辑ID
      ;(formData as any).book_id = props.editData.id
      
      // 设置桌台选择状态
      selectedDeskIds.value = data.deskIds || []
      selectedDeskCount.value = selectedDeskIds.value.length
      
      console.log('通过API查询填充编辑数据:', data)
    } else {
      ElMessage.error('获取预约详情失败')
    }
  } catch (error) {
    console.error('查询预约详情失败:', error)
    ElMessage.error('获取预约详情失败')
  }
}

// 处理手机号输入
function handleMobileInput(value: string) {
  // 只允许输入数字
  const numericValue = value.replace(/\D/g, '')
  if (numericValue !== value) {
    formData.mobile = numericValue
  }
}

function openDesktopList() {
  if (!formData.book_time) {
    ElMessage.warning('请先选择预订时间')
    return
  }
  showDeskList.value = true
}

// 打开点菜页面
function openFoodOrder() {
  if (!canOpenFoodOrder.value) {
    ElMessage.warning('请先填写顾客姓名、联系电话、用餐人数和用餐时间')
    return
  }
  
  // 保存当前预订数据到本地存储
  const bookData = {
    ...formData,
    deskIds: selectedDeskIds.value,
    book_id: props.editData?.id || null,
    tempId: Date.now(), // 临时ID，用于标识这次预订
    foodList: [],
    fromBookDialog: true // 标识来源
  }
  
  // 使用 sessionStorage 保存数据，页面刷新后仍然存在
  sessionStorage.setItem('bookDialogData', JSON.stringify(bookData))
  
  // 跳转到点菜页面，传递临时ID作为桌台ID
  router.push({
    path: `/home/diancai/${bookData.tempId}`,
    query: {
      fromPage: 'appointmentPage',
      bookId: bookData.tempId
    }
  })
  
  // 关闭当前弹框
  isShowDialog.value = false
}

async function loadDeskList() {
  if (!formData.book_time) return
  deskListLoading.value = true
  try {
    const res = await deskBookDeskList({ book_time: formData.book_time })
    if (res?.status === 200) {
      const list = res?.data?.list || []
      list.forEach((item: any) => (item.isChecked = selectedDeskIds.value.includes(item.id)))
      deskList.value = list
      // 同步一次计数
      selectedDeskCount.value = selectedDeskIds.value.length
      formData.book_num = selectedDeskCount.value
    }
  } catch (error) {
    console.error('加载桌台列表失败:', error)
    ElMessage.error('加载桌台列表失败')
  } finally {
    deskListLoading.value = false
  }
}

function onCancel() {
  isShowDialog.value = false
}

async function onConfirm() {
  await formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    confirmLoading.value = true
    try {
      const datas: any = {
        user_name: formData.user_name,
        mobile: formData.mobile,
        use_num: formData.use_num,
        book_time: formData.book_time,
        keep_time: formData.keep_time,
        book_type: formData.book_type,
        book_money: formData.book_money || 0,
        settle_type: formData.settle_type,
        money: formData.money,
        book_num: formData.book_num,
        book_user_id: formData.subscription, // 代订人（如有）
        deskIds: formData.deskIds, // 选中的桌台ID集合
        remark: formData.remark,
        pay_type: formData.pay_type,
        selectedFoods: formData.selectedFoods, // 选择的菜品
        food_list: formData.foodList
      }
      let resp
      if (isEdit.value && (formData as any).book_id) {
        datas.book_id = (formData as any).book_id
        resp = await deskBookEdit(datas)
      } else {
        resp = await deskBookAdd(datas)
      }
      if (resp?.status === 200) {
        ElMessage.success(isEdit.value ? '修改预订成功' : '新增预订成功')
        emit('onConfirmSuccess')
        isShowDialog.value = false
      }
    } finally {
      confirmLoading.value = false
    }
  })
}

watch(isShowDialog, val => {
  if (val) {
    if (isEdit.value && props.editData) {
      // 编辑模式：填充编辑数据
      fillEditData()
    } else {
      // 新增模式：重置所有字段
      formData.user_name = ''
      formData.mobile = ''
      formData.use_num = null
      formData.book_time = ''
      formData.keep_time = null
      formData.book_type = null
      formData.book_money = null
      formData.settle_type = null
      formData.money = null
      formData.book_num = 0
      formData.pay_type = ''
      formData.remark = ''
      formData.deskIds = []
      formData.selectedFoods = []
      formData.foodList = []
      // 重置选择状态
      selectedDeskCount.value = 0
      selectedDeskIds.value = []
      deskList.value = []

      // 自动设置代订人为当前登录用户
      formData.subscription = userStore.userInfo?.real_name || ''
    }
    handleReturnFromFoodOrder()


    // 加载下拉选项数据
    // loadPaymentList()
    // loadTypeList()
  }
})

watch(
  () => showDeskList.value,
  v => {
    if (v) loadDeskList()
  }
)

// 监听编辑数据变化
watch(
  () => props.editData,
  (newData) => {
    if (isShowDialog.value && isEdit.value && newData) {
      fillEditData()
    }
  },
  { deep: true }
)

async function loadPaymentList() {
  try {
    const params = {
      balance: '会员支付',
      cash: '现金支付',
      alipay: '支付宝',
      wechat: '微信',
      on_account: '挂账',
      integripay: '积分支付'
    }
    const res = await paymentList(params)
    if (res?.status === 200) {
      const data = res.data || []
      payTypeOptions.value = data.map((item: any) => {
        if (item.method === 'virtual') {
          return { value: item.method, label: item.others?.name || '虚收' }
        }
        return { value: item.method, label: params[item.method] || item.method }
      })
    }
  } catch (e) {}
}

async function loadTypeList() {
  try {
    const res = await deskBookTypeList()
    if (res?.status === 200) {
      const data = res?.data?.list || []
      typeOptions.value = data
    }
  } catch (e) {}
}

watch(isShowDialog, val => {
  if (val) {
    loadPaymentList()
    loadTypeList()
  }
})

function toggleDesk(d: any) {
  d.isChecked = !d.isChecked
  // 即点即同步
  const ids = deskList.value.filter((x: any) => x.isChecked).map((x: any) => x.id)
  selectedDeskIds.value = ids
  selectedDeskCount.value = ids.length
  formData.book_num = selectedDeskCount.value
  formData.deskIds = ids
}

// 处理从点菜页面返回的数据
function handleReturnFromFoodOrder() {
  const bookDialogData = sessionStorage.getItem('bookDialogData')
  if (bookDialogData) {
    try {
      const data = JSON.parse(bookDialogData)
      if (data) {
        // 恢复预订数据
        Object.assign(formData, {
          book_id: data.book_id || null,
          user_name: data.user_name || '',
          mobile: data.mobile || '',
          use_num: data.use_num || null,
          book_time: data.book_time || '',
          keep_time: data.keep_time || null,
          book_type: data.book_type || null,
          book_money: data.book_money || null,
          settle_type: data.settle_type || null,
          money: data.money || null,
          book_num: data.book_num || 0,
          pay_type: data.pay_type || '',
          remark: data.remark || '',
          deskIds: data.deskIds || [],
          subscription: data.subscription || '',
          selectedFoods: data.selectedFoods || [],
          foodList: data.foodList || []
        })
        
        // 恢复桌台选择状态
        selectedDeskIds.value = data.deskIds || []
        selectedDeskCount.value = selectedDeskIds.value.length
        // 清除临时数据
        sessionStorage.removeItem('bookDialogData')
        console.log('从点菜页面返回，恢复预订数据:', data)
      }
    } catch (error) {
      console.error('解析返回数据失败:', error)
      sessionStorage.removeItem('bookDialogData')
    }
  }
}

// 组件挂载时检查是否有返回数据
onMounted(() => {
  
})

</script>
<style scoped lang="scss">
.dialog-content {
  width: 1200px;
  .title {
    font-size: 20px;
    font-weight: 700;
    color: #000;
    margin-bottom: 10px;
  }
  .form-box {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px 24px;
    .form-item {
      display: flex;
      align-items: center;
      .label {
        min-width: 100px;
        margin-right: 10px;
        font-size: 14px;
        color: #333;
        > span {
          color: #7c0a03;
        }
      }
      .input,
      .select {
        width: 260px;
      }
    }
  }
  .footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  .big-btn {
    width: 100%;
    padding: 0 32px;
    border-radius: 12px;
    font-size: 16px;
  }
  .big-btn.lg {
    height: 52px;
    font-size: 18px;
  }
  .footer-btn.lg {
    height: 52px;
    padding: 0 28px;
    font-size: 18px;
    border-radius: 12px;
  }
}
.desk-dialog {
  .desk-header {
    font-size: 18px;
    font-weight: 700;
    color: #000;
    margin-bottom: 10px;
  }
  .desk-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
    max-height: 420px;
    overflow-y: auto;
  }
  .desk-item {
    border: 1px solid #d2d2d2;
    border-radius: 12px;
    padding: 12px;
    cursor: pointer;
    background: #fff;
    .desk-name {
      font-size: 18px;
      font-weight: 700;
      color: #434447;
    }
    .desk-capacity {
      margin-top: 8px;
      color: #666;
    }
    .desk-status {
      margin-top: 6px;
      color: #999;
    }
  }
  .desk-item.active {
    border-color: #7c0a03;
    box-shadow: 0 0 0 2px rgba(124, 10, 3, 0.1);
  }
  .no-data {
    color: #999;
    padding: 30px 0;
    text-align: center;
  }
}
/* 旧项目选择桌台样式（原样迁移） */
.select-desktop-wrap {
  // width: 1354px;
  max-height: 388px;
  background: #f4f4f4;
  box-sizing: border-box;
  padding: 20px 24px 0 24px;
  overflow-y: auto;
  margin-top: 30px;
}
.room-selected-box {
  box-sizing: border-box;
  overflow-y: auto;
  background: #f4f4f4;
  min-width: 990px;
}
.room-selected-scroll-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  justify-content: space-between;
}
.scroll-selected-list-item {
  position: relative;
  width: 220px;
  height: 210px;
  background: #ffffff;
  border: 1px solid #d2d2d2;
  border-radius: 12px;
  box-sizing: border-box;
  border-top: none;
  margin-top: 20px;
  cursor: pointer;
}
.scroll-selected-list-item .title-box {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 43px;
  background: #d2d2d2;
  padding: 0 12px;
  font-size: 13px;
  font-family:
    PingFang SC,
    PingFang SC-Bold;
  font-weight: 700;
  color: #ffffff;
  border-radius: 12px 12px 0px 0px;
}
.scroll-selected-list-item .title-box .count {
  display: flex;
  align-items: center;
}
.scroll-selected-list-item .desc-box {
  padding: 10px 0 0 12px;
}
.scroll-selected-list-item .numberAndTag {
  display: flex;
  align-items: flex-start;
}
.scroll-selected-list-item .numberAndTag .number {
  font-size: 34px;
  font-family:
    PingFang SC,
    PingFang SC-Bold;
  font-weight: 700;
  color: #434447;
}
.scroll-list-item-zhanwei {
  width: 220px;
  overflow: hidden;
}
.choose-img {
  position: absolute;
  right: 12px;
  bottom: 12px;
  width: 24px;
  height: 24px;
}
.count-selected-box {
  height: 60px;
  box-sizing: border-box;
  background: #f4f4f4;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 14px;
  font-family:
    PingFang SC,
    PingFang SC-Regular;
  font-weight: 400;
  color: #333333;
}

/* 骨架屏样式 */
.desk-skeleton-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 20px 0;
}

.skeleton-desk-item {
  margin-top: 20px;
}

/* 无数据状态样式 */
.no-desk-data {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  background: #f4f4f4;
  border-radius: 12px;
}

.no-data-text {
  font-size: 16px;
  color: #999;
  text-align: center;
}
</style>
<style>
.bookCreateDialog-box {
  max-height: unset !important;
}
</style>
